﻿@using System.Text.Json

<MRow Dense Class="mb-2">
    <MCol Cols="6">
        <MButton OnClick="OnLoadDefault">Load default data</MButton>
    </MCol>
    <MCol Cols="6">
        <MButton OnClick="OnSave">Save current data</MButton>
    </MCol>
    <MCol Cols="6">
        <MButton OnClick="OnClear">Clear grids</MButton>
    </MCol>
    <MCol Cols="6">
        <MButton OnClick="OnLoad">Load saved data</MButton>
    </MCol>
</MRow>

<MGridstack Items="@_items"
            ItemKey="item => item.ToString()"
            ItemClass="blue"
            Margin="6"
            TItem="int"
            ItemPosition="@_itemPosition"
            DisableOneColumnMode
            @ref="@_gridstack">
    <ItemContent>
        <div class="text-center">@context</div>
    </ItemContent>
</MGridstack>

<MDivider />

<MTextarea Readonly
           Filled
           HideDetails="true"
           Label="Saved data"
           Rows="20"
           Value="@(JsonSerializer.Serialize(_widgets, new JsonSerializerOptions() { WriteIndented = true }))"
           Class="gridstack-save-and-load__textarea ma-1">
</MTextarea>

@code {

    private List<int> _items = new();

    private MGridstack<int>? _gridstack;
    private List<GridstackWidget> _widgets = new();
    private Func<int, GridstackWidgetPosition> _itemPosition = DefaultItemPosition;

    private async Task OnSave()
    {
        _widgets = await _gridstack!.OnSave();
    }

    private void OnClear()
    {
        _items.Clear();
    }

    private void OnLoad()
    {
        _items = _widgets.Select(w => Convert.ToInt32(w.Id)).ToList();
        _itemPosition = id =>
        {
            var widget = _widgets.FirstOrDefault(w => w.Id == id.ToString());
            return widget ?? new GridstackWidgetPosition(2, 2);
        };
    }

    private void OnLoadDefault()
    {
        _items = Enumerable.Range(1, 11).ToList();
        _itemPosition = DefaultItemPosition;
    }

    static GridstackWidgetPosition DefaultItemPosition(int item)
    {
        return item switch
        {
            1 => new(4, 2),
            2 => new(4, 4),
            6 => new(2, 4),
            7 => new(4, 2),
            9 => new(4, 2),
            _ => new(2, 2)
        };
    }

}

<style>
    .gridstack-save-and-load__textarea textarea {
      line-height: 1;
      font-family: monospace;
      font-size: small;
    }
</style>
